<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="searchForm" :model="searchForm" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="仓库名称">
              <el-input
                v-model="searchForm.warehouseName"
                placeholder="请输入仓库名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门">
              <el-select
                v-model="searchForm.unitId"
                clearable
                placeholder="请输入"
              >
                <el-option
                  v-for="item in departList"
                  :key="item.unitId"
                  :label="item.unitName"
                  :value="item.unitId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="6" :span="6" class="text-right">
            <el-button
              icon="iconfont iconxianxing_sousuo"
              type="primary"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button
              icon="iconfont iconxianxing_zhongzhi"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-col>
          <el-col :span="24" class="text-left">
            <el-button type="primary" @click="onAdd">
              新增仓库
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <Table
        ref="table"
        :current-page="page"
        :header-data="tableHeader"
        :index="false"
        :loading="loading"
        :page-size="limit"
        :table-data="tableData"
        :total="total"
        class="data-table"
        style="width: 100%"
        @now-page="handlePage"
        @now-size="handleSize"
        @table-sort="handleSort"
      />
    </el-main>
    <el-drawer :title="title" :visible.sync="drawerVisible">
      <div class="drawer-main">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-position="top"
          label-width="80px"
        >
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input
              v-model="form.warehouseName"
              placeholder="请输入"
              :disabled="form.id"
            />
          </el-form-item>
          <el-form-item label="仓库地址" prop="warehouseAddress">
            <el-input v-model="form.warehouseAddress" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属部门" prop="unitId" required>
            <el-select
              v-model="unitName"
              placeholder="请输入"
              value-key="unitId"
              @change="(val) => onChange(val, 'unitName', 'unitId')"
            >
              <el-option
                v-for="item in departList"
                :key="item.unitId"
                :label="item.unitName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              placeholder="请输入"
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="type !== 'look'" class="drawer-footer">
        <div class="footer-btn">
          <el-button type="primary" @click="handleSubmit"> 确认</el-button>
          <el-button @click="onCancel"> 取消</el-button>
        </div>
      </div>
    </el-drawer>

    <el-drawer :title="title" :visible.sync="drawerTableVisible" size="50%">
      <div class="drawer-main">
        <Manager
          ref="Manager"
          :warehouse-info="warehouseInfo"
          @selectList="onSelectList"
        />
      </div>
      <div class="drawer-footer">
        <div class="footer-btn">
          <el-button type="primary" @click="handleSubmitMan"> 确认</el-button>
          <el-button @click="onCancelMan"> 取消</el-button>
        </div>
      </div>
    </el-drawer>
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import {
  getWarehouseList,
  postWarehouseDel,
  postWarehouseAdd,
  postWarehouseUpdate,
  getDepartList,
  setAdmins,
} from "./api";
import { parseTime } from "@/utils";
import Manager from "./manager";

export default {
  name: "WarehouseList",
  components: {
    Manager,
  },
  mixins: [addTable],
  data() {
    return {
      searchForm: {
        unitId: "",
        warehouseName: "",
      },
      adminsList: [],
      unitName: {},
      title: "",
      type: "look",
      tableHeader: [],
      departList: [],
      drawerVisible: false,
      drawerTableVisible: false,
      form: {
        id: "",
        warehouseName: "",
        warehouseAddress: "",
        remark: "",
        unitName: "",
        unitId: null,
      },
      rules: {
        warehouseName: [{ required: true, message: "仓库名称必填" }],
        unitId: [{ required: true, message: "所属部门必填" }],
      },
      managerList: [],
      warehouseInfo: {},
    };
  },
  created() {
    this.tableHeader = [
      {
        prop: "warehouseName",
        label: "仓库名称",
        sortable: false,
        overflow: true,
        width: 180,
        align: "left",
      },
      {
        prop: "warehouseAddress",
        label: "仓库地址",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "admins",
        label: "仓库管理员",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "unitName",
        label: "所属部门",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "remark",
        label: "备注",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "createdTime",
        label: "创建时间",
        sortable: false,
        overflow: true,
        align: "left",
        width: 180,
        render: (h, vm) => {
          const time = vm.createdTime ? parseTime(vm.createdTime) : "";
          return <span>{time}</span>;
        },
      },
      {
        width: 200,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          return [
            {
              text: "设置管理员",
              type: "text",
              event: this.onManager,
            },
            // {
            //   text: '详情',
            //   type: 'text',
            //   event: this.onDetail
            // },
            {
              text: "编辑",
              type: "text",
              event: this.onEdit,
            },
            // {
            //   text: '删除',
            //   type: 'text',
            //   event: this.onDelete
            // }
          ];
        },
      },
    ];
    this.getDepartList();
    this.getTableData();
  },

  methods: {
    async onChange(val, type, id) {
      this.form[type] = val[type];
      this.form[id] = val[id];
    },
    async getDepartList() {
      const { data } = await getDepartList({
        page: 1,
        limit: 1000,
      });
      this.departList = data;
    },
    onDetail(row) {
      this.form = {
        ...row,
      };
      this.type = "look";
      this.title = "查看详情";
      this.drawerVisible = true;
    },
    onWarehouse(row) {
      this.$router.push({
        name: "goodsStore",
        query: {
          id: row.id,
        },
      });
    },
    async onManager(row) {
      this.type = "look";
      this.title = "设置管理员";
      this.drawerTableVisible = true;
      this.warehouseInfo = { ...row };
    },
    onEdit(row) {
      this.form = {
        ...row,
      };
      this.type = "edit";
      this.title = "编辑仓库";
      this.drawerVisible = true;
    },
    onAdd() {
      this.form = {};
      this.type = "add";
      this.title = "新增仓库";
      this.drawerVisible = true;
    },
    onDelete(row) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        postWarehouseDel({ id: row.id })
          .then(({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.getTableData();
          })
          .catch();
      });
    },
    getTableData() {
      this.loading = true;
      this.getTableParams();
      getWarehouseList(this.tableParams)
        .then((res) => {
          if (!res) return;
          const { data, pageInfo } = res;
          setTimeout(() => {
            this.loading = false;
            this.tableData = data;
            this.total = pageInfo.total;
          }, 500);
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.id
            ? postWarehouseUpdate(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.drawerVisible = false;
                this.form = {};
                this.getTableData();
              })
            : postWarehouseAdd(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.drawerVisible = false;
                this.form = {};
                this.getTableData();
              });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    onCancel() {
      this.drawerVisible = false;
      this.$refs.form.resetFields();
    },
    onCancelMan() {
      this.managerList = [];
      this.drawerTableVisible = false;
    },
    onSelectList(val) {
      console.log(111, this.warehouseInfo);
      console.log(234234, val);
      this.managerList =
        val.length > 0
          ? val.map((item) => {
              item.warehouseName = this.warehouseInfo.warehouseName;
              item.warehouseId = this.warehouseInfo.id;
              return item;
            })
          : [];
    },
    handleSubmitMan() {
      setAdmins({
        warehouseId: this.warehouseInfo.id,
        managerList: this.managerList,
      }).then(({ success, message }) => {
        if (success) {
          this.$message.success(message);
        } else {
          this.$message.error(message);
        }
        this.managerList = [];
        this.drawerTableVisible = false;
        this.getTableData();
      });
    },
  },
};
</script>
